# -*- coding: utf-8 -*-

import pypinyin,os,re,codecs

filedict={}

def walk(startdir, ext, func):
    for dirpath, dirnames, filenames in os.walk(startdir):
        for filename in filenames:
            splitename=os.path.splitext(filename)
            if len(splitename)!=2:
                continue
            if splitename[1] == ext:
                func(startdir,dirpath,splitename[0],splitename[1])

def initStaticCache(startdir,dirpath,filename,ext):
    pinyinpath=pypinyin.slug(unicode(filename, 'gbk'))+ext
    relpath=os.path.relpath(dirpath, startdir)
    filedict[unicode(relpath + "/" + filename+ext,'gbk')]=relpath.replace('\\','/')+'/'+pinyinpath

def renameStaticName(startdir,dirpath,filename,ext):
    filepath=dirpath+"/"+filename+ext
    content=''
    with codecs.open(dirpath+"/"+filename+ext,'r',encoding='UTF-8') as f:
        content=''.join(f.readlines())
        for (k,v) in filedict.items():
            k1=re.sub(ur'\\|/',ur'/',k)
            k2=re.sub(ur'\\|/',ur'\\',k)
            content=content.replace(k1, v)
            content=content.replace(k2, v)
            print 'revicing ',filepath,'......\n'
    if len(content) > 0:
        with codecs.open(dirpath+"/"+filename+ext,'w',encoding='UTF-8') as f:
            f.write(content)

if __name__=="__main__":
    walk("c:/temp", ".png", initStaticCache)
    walk("c:/temp", ".rst", renameStaticName)

    
